/**
 * fshows.com
 * Copyright (C) 2013-2020 All Rights Reserved.
 */
package com.fshows.leshuapay.sdk.util;

import com.google.common.base.CaseFormat;
import com.google.common.collect.Iterables;

import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import java.text.MessageFormat;
import java.util.Set;

/**
 * @author wujn
 * @version ValidateUtil.java, v 0.1 2020-04-27 6:09 PM wujn
 */
public class ValidateUtil {

    private static final Validator VALIDATOR = Validation.buildDefaultValidatorFactory().getValidator();

    /**
     * 验证参数
     *
     * @param object
     * @param <T>
     * @return
     */
    public static <T> ValidateResult validate(T object, Class<?>... classes) {
        ValidateResult validateResult = new ValidateResult();
        validateResult.setResult(true);
        //执行验证
        Set<ConstraintViolation<T>> constraintViolations = VALIDATOR.validate(object, classes);
        //如果有验证信息，则将第一个取出来包装成异常返回
        ConstraintViolation<T> constraintViolation = Iterables.getFirst(constraintViolations, null);
        if (constraintViolation != null) {
            validateResult.setResult(false);
            validateResult.setParamName(CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, constraintViolation.getPropertyPath().toString()));
            validateResult.setMsg(constraintViolation.getMessage());
        }
        return validateResult;
    }

    /**
     * 验证参数，如果不符合抛出异常
     *
     * @param request
     * @param <T>
     * @return
     */
    public static <T> void validateWithThrow(T request, Class<?>... classes) {
        // 参数校验
        ValidateResult validate = validate(request, classes);
        if (!validate.isResult()) {
            throw new IllegalArgumentException(MessageFormat.format("错误参数，param={0}，msg={1}", validate.getParamName(), validate.getMsg()));
        }
    }
}
